<template>
    <div class="user-edit all-height">
        <!-- Drawer抽屉 -->
        <!-- <Drawer
        :title="title"
        v-model="visible"
        width="720"
        draggable
        :mask-closable="type == '0'"
    > -->
        <div :style="{ maxHeight: maxHeight }" class="drawer-content all-height">
            <div class="drawer-header">
                <div class="cmr16"  v-show="type == '2'">院校新增</div>
                <div class="cmr16" v-show="type != '2'">编辑区</div>
                <!-- <Avatar :src="form.avatar" size="large" v-show="type != '2'"/> -->
            </div>
            <Form label-colon v-show="type != '2'" label-position="right" :label-width="labelWidth100">
                <Row :gutter="32">
                    <Col span="24">
                        <FormItem label="账号">
                            {{ form.username }}
                            <Tooltip trigger="hover" placement="right" content="账户已禁用">
                                <Icon v-show="form.status == -1" type="md-lock" size="18" class="icon01" />
                            </Tooltip>
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="所在高校">
                            {{ form.gxmc }}
                        </FormItem>
                    </Col>
                </Row>
            </Form>

            <Form ref="form" :model="form" :rules="formValidate" label-position="right" :label-width="labelWidth120">
                <Row :gutter="32" v-if="type == '2'">
                    <Col span="24" v-if="type == '2'">
                        <FormItem label="院校名称" prop="gxcode" :rules="{ required: true, message: '不能为空', trigger: 'change' }">
                            <Select v-model="form.gxcode" :transfer="true" clearable filterable @on-change="changeBackTask" label-in-value="true">
                                <Option v-for="item in schoolList" :key="item.id" :value="item.code">{{ item.name }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="账号" prop="username" style="position: relative">
                            <Input v-model="form.username" autocomplete="off" placeholder="请先选择学校" :maxlength="16" />
                            <!--              <input type="text" style="position: fixed;z-index: -10000;width: 0;border: none"></input>-->
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="密码" prop="password">
                            <SetPassword v-model="form.password" @on-change="changePass" />
                        </FormItem>
                    </Col>
                </Row>

                <Row :gutter="32">
                    <Col span="24">
                        <FormItem label="姓名" prop="name">
                            <Input v-model="form.name" />
                        </FormItem>
                    </Col>
                </Row>
                <Row :gutter="32">
                    <Col span="24">
                        <FormItem label="角色" prop="roleIds">
                            <Select v-model="form.roleIds" multiple transfer max-tag-count="1">
                                <Checkbox @on-change="roleIdsClickAll" v-model="roleIdsAll">全选</Checkbox>

                                <Option v-for="item in roleList" :value="item.id" :key="item.id" :label="item.description">
                                    <span style="margin-right: 10px">{{ item.name }}</span>
                                    <span style="color: #ccc">{{ item.description }}</span>
                                </Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="管理的学历层次" prop="glxlcc" :rules="{ required: true, trigger: 'change', validator: validateGlxlcc }">
                            <Select v-model="form.glxlcc" filterable multiple>
                                <checkbox v-model="glxlccChecked" @on-change="selectGlxlccAllOptions">全选</checkbox>
                                <Option v-for="item in glxlccList" :value="item.value" :key="item.id">{{ item.title }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="职务" prop="zw">
                            <Input v-model="form.zw" clearable />
                        </FormItem>
                    </Col>
                </Row>
                <Row :gutter="32">
                    <Col span="24">
                        <FormItem label="手机号" prop="mobile">
                            <Input v-model="form.mobile" />
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="电话" prop="telephone">
                            <Input v-model="form.telephone" clearable />
                        </FormItem>
                    </Col>
                </Row>
                <Row :gutter="32">
                    <Col span="24">
                        <FormItem label="部门名称" prop="sectionName">
                            <Input v-model="form.sectionName" clearable />
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="部门负责人姓名" prop="sectionPerson">
                            <Input v-model="form.sectionPersonName" clearable />
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="负责人手机号" prop="sectionMobile">
                            <Input v-model="form.sectionPersonMobile" clearable />
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="传真" prop="fax">
                            <Input v-model="form.fax" clearable />
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="邮箱">
                            <Input v-model="form.email" transfer />
                        </FormItem>
                    </Col>
                </Row>
                <Row :gutter="32">
                    <Col span="24">
                        <FormItem label="QQ" prop="qq">
                            <Input v-model="form.qq" clearable />
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="排序值" prop="sortorder">
                            <Input v-model="form.sortorder" clearable />
                        </FormItem>
                    </Col>
                </Row>
            </Form>
        </div>
        <div class="br right-bottom-edit">
            <Button type="text" @click="cancel">取消</Button>

            <div v-if="type == '1'" style="display: inline">
                <Button v-has="'edit'" type="primary" :loading="submitLoading" @click="submit">提交</Button>
            </div>
            <div v-if="type == '2'" style="display: inline">
                <Button v-has="'add'" type="primary" :loading="submitLoading" @click="submit">提交</Button>
            </div>
        </div>
        <!-- </Drawer> -->
    </div>
</template>

<script>
import { addSchoolPersonInfo, editSchoolPersonInfo } from '@/api/bys/personInfo/school';
import { getDictDataByType, getRoles as getRoleList } from '@/api/index';
import { validateUsername, validateMobileNoBt, checkEmail, validatePassword } from '@/libs/validate';
import departmentTreeChoose from '@/views/my-components/xboot/department-tree-choose';
import uploadPicInput from '@/views/my-components/xboot/upload-pic-input';
import SetPassword from '@/views/my-components/xboot/set-password';
import dict from '@/views/my-components/xboot/dict';
import { getNode } from '@/api/activiti';
import select from 'view-design/src/components/select';
import { it } from 'date-fns/locale';
import Cookies from 'js-cookie';

export default {
    name: 'user',
    computed: {
        select() {
            return select;
        }
    },
    components: {
        departmentTreeChoose,
        uploadPicInput,
        SetPassword,
        dict
    },
    props: {
        value: {
            type: Boolean,
            default: false
        },
        data: {
            type: Object
        },
        type: {
            type: String,
            default: '0'
        }
    },
    data() {
        return {
            validateGlxlcc: (rule, value, callback) => {
                if (this.form.glxlcc.length > 0) {
                    callback();
                } else {
                    callback(new Error('请选择管理得学历层次'));
                }
            },
            labelWidth100: 100,
            labelWidth120: 120,
            roleIdsAll: false, //角色全选
            glxlccChecked: false,
            roleList: [],
            visible: this.value,
            title: '',
            passColor: '',
            submitLoading: false,
            maxHeight: 510,
            glxlccList: [],
            form: {
                type: 0,
                address: []
            },
            formValidate: {
                // 表单验证规则
                username: [
                    { required: true, message: '请输入账号', trigger: 'blur' },
                    { validator: validateUsername, trigger: 'blur' }
                ],
                name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { validator: validatePassword, trigger: 'blur' }
                ],
                mobile: [
                    // { required: true, message: "请输入手机号", trigger: "change" },
                    { validator: validateMobileNoBt, trigger: 'blur' }
                ],
                sectionMobile: [{ validator: validateMobileNoBt, trigger: 'blur' }],

                email: [
                    // { required: true, message: "请输入邮箱地址" },
                    { validator: checkEmail, trigger: 'blur' }
                ],
                schoolList: []
            }
        };
    },
    methods: {
        roleIdsClickAll() {
            if (this.roleIdsAll) {
                this.form.roleIds = this.roleList.map(option => option.id);
            } else {
                this.form.roleIds = [];
            }
        },
        init() {
            this.getRoleList();
            this.getSchoolList();
            this.getGlxlccDictList();
        },
        getSchoolList() {
            this.loading = true;
            let userinfo=JSON.parse(Cookies.get('userInfo'))
            if(userinfo.resource == 1){
                this.postRequest('/schoolCode/getAllNoProvince').then(res => {
                    if (res.success) {
                        this.loading = false;
                        this.schoolList = res.result;
                    }
                });
            }else{
                this.postRequest('/schoolCode/getAll').then(res => {
                    if (res.success) {
                        this.loading = false;
                        this.schoolList = res.result;
                    }
                });
            }

        },
        getRoleList() {
            getRoleList({ level: 'admin' }).then(res => {
                if (res.success) {
                    this.form.roleIds = res.result[0].id;
                    this.roleList = res.result;
                    this.roleList.shift();
                }
            });
        },
        // handleSelectDepTree(v) {
        //   this.form.departmentid = v;
        //   this.form.departmenttitle = this.$refs.depTree.departmentTitle;
        // },
        changePass(v, grade, strength) {
            this.form.passStrength = strength;
            this.form.password = v;
        },
        submit() {
            console.log(this.form);
            this.$refs.form.validate(valid => {
                if (valid) {
                    // this.form.mobile = this.getMockMobile();
                    if (typeof this.form.birth == 'object') {
                        this.form.birth = this.format(this.form.birth, 'yyyy-MM-dd');
                    }
                    if (this.type == '1') {
                        // 编辑
                        this.submitLoading = true;
                        editSchoolPersonInfo(this.form).then(res => {
                            this.submitLoading = false;
                            if (res.success) {
                                this.$Message.success('操作成功');
                                this.$emit('on-submit', true);
                                this.visible = false;
                                this.cancel();
                            }
                        });
                    } else {
                        // 添加
                        this.submitLoading = true;
                        addSchoolPersonInfo(this.form).then(res => {
                            this.submitLoading = false;
                            if (res.success) {
                                this.$Message.success('操作成功');
                                this.$emit('on-submit', true);
                                this.visible = false;
                                this.cancel();
                            }
                        });
                    }
                }
            });
        },
        cancel() {
            this.$emit('open-search', true);
        },
        setCurrentValue(value) {
            if (value === this.visible) {
                return;
            }
            if (this.type == '1') {
                this.title = '编辑用户';
                this.maxHeight = Number(document.documentElement.clientHeight - 121) + 'px';
            } else if (this.type == '2') {
                this.title = '添加用户';
                this.maxHeight = Number(document.documentElement.clientHeight - 121) + 'px';
            } else {
                this.title = '用户详情';
                this.maxHeight = '100%';
            }
            // 清空数据
            this.$refs.form.resetFields();
            if (this.type == '0' || this.type == '1') {
                // 回显数据
                let data = this.data;
                // 部门
                // this.$refs.depTree.setData(data.departmentid, data.departmenttitle);
                // 角色
                let selectRolesId = [];
                if (data.roles) {
                    data.roles.forEach(function (e) {
                        selectRolesId.push(e.id);
                    });
                }
                data.roleIds = selectRolesId;
                delete data.roles;
                delete data.permissions;
                // 密码强度
                if (data.passStrength == '弱') {
                    this.passColor = '#ed3f14';
                } else if (data.passStrength == '中') {
                    this.passColor = '#faad14';
                } else if (data.passStrength == '强') {
                    this.passColor = '#52c41a';
                }
                // 回显
                this.form = data;
                this.form.glxlcc = this.form.glxlcc.split(',');
            } else {
                // // 添加
                // this.$refs.depTree.setData("", "");
                // this.form = {
                //   type: 0,
                //   sex: "",
                //   address: [],
                // };
            }
            this.visible = value;
        },
        // 生成假手机号
        getMockMobile() {
            const mobilePrefix = '152';
            let mobileSuffix = '';
            for (let i = 0; i < 8; i++) {
                mobileSuffix += Math.floor(Math.random() * 10);
            }
            // console.log(mobilePrefix + mobileSuffix);
            return mobilePrefix + mobileSuffix;
        },
        getGlxlccDictList() {
            // 学历层次
            getDictDataByType('eduLevelType').then(res => {
                if (res.success) {
                    this.glxlccList = res.result;
                }
            });
        },
        changeBackTask(v) {
            this.form.gxmc = v.label;
            this.form.username = v.value;
            this.$refs.form.validateField('username');
            this.glxlccChecked = true;
            this.selectGlxlccAllOptions();
        },
        selectGlxlccAllOptions() {
            if (this.glxlccChecked) {
                this.form.glxlcc = this.glxlccList.map(item => item.value);
            } else {
                this.form.glxlcc = '';
            }
        },
        onRestWindow() {
            this.labelWidth120 = this.searchLabelWidth(this.labelWidth120)
            this.labelWidth100 = this.searchLabelWidth(this.labelWidth100)
            
        },
    },
    watch: {
        data(val) {
            this.setCurrentValue(val);
        },
        visible(value) {
            // if(value){
            //   this.form={}
            // }
            this.$emit('input', value);
        },
        form: {
            deep: true,
            handler() {
                if (this.form.glxlcc) {
                    if (this.form.glxlcc.length === this.glxlccList.map(item => item.value).length) {
                        this.glxlccChecked = true;
                    } else {
                        this.glxlccChecked = false;
                    }
                }
            }
        },
       
    },
    mounted() {
        this.onRestWindow()
        window.addEventListener('resize',this.onRestWindow)
        this.init();
    },
    beforeDestroy() {
        window.removeEventListener('resize',this.onRestWindow)
    }
};
</script>

<style lang="less">
@import '../../../styles/drawer-common.less';
@import '../../personInfo.less';
.ivu-form-item {
    margin-bottom: 0.1rem;
}
.ivu-input-prefix {
    top: 0.03rem;
}
</style>
<style lang="less" scoped>
.cmr16 {
    margin-right: 16px
}
.cml10 {
    margin-left: 10px;
}

.icon01 {
    margin-left: 10px; cursor: pointer
}
</style>